<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <title>订单支付</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <script src="/js/vue.js"></script>
  <!--vue提供的生成二维码的组件-->
  <script src="/js/vue-qriously.js"></script>
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <script src="/js/index.js"></script>
  <script src="/js/axios.min.js"></script>
  <style>
    body { background:#f5f7fa; }
    .page { max-width: 800px; margin: 20px auto; }
    .title-row { display:flex; align-items:center; justify-content:space-between; margin-bottom:14px; }
    .title { font-size:16px; font-weight:600; color:#303133; display:flex; align-items:center; }
    .title::before { content:""; width:4px; height:14px; background:#67c23a; border-radius:2px; margin-right:8px; }

    .order-info { display:grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; margin-bottom: 20px; }
    .info-item { color:#606266; margin-bottom:8px; }
    .info-item b { color:#303133; margin-right:6px; }

    .amount { font-size:24px; color:#f56c6c; font-weight:700; text-align:center; margin:20px 0; }

    .pay-method { border:2px solid #e4e7ed; border-radius:8px; padding:15px; cursor:pointer; text-align:center; transition:all 0.3s; }
    .pay-method:hover { border-color:#409eff; }
    .pay-method.active { border-color:#409eff; background:#ecf5ff; }

    .qr-container { text-align:center; padding:20px; background:#fff; border-radius:8px; margin:20px 0; }
    .qr-code { margin:20px auto; width: 200px; height: 200px; }
    .countdown { font-size:18px; color:#f56c6c; margin:10px 0; }
    .pay-status { text-align:center; padding:40px; }

    .footer-bar { display:flex; align-items:center; justify-content:space-between; padding:20px 0; }
  </style>
</head>
<body>
<div id="app" class="page">
  <!-- 顶部 -->
  <div class="title-row">
    <div class="title">订单支付</div>
    <div>
      <el-button size="mini" icon="el-icon-arrow-left" @click="goBack">返回</el-button>
    </div>
  </div>

  <!-- 订单信息 -->
  <el-card shadow="always" style="margin-bottom:14px;" v-loading="loading">
    <div class="title">订单信息</div>
    <div class="order-info" v-if="order">
      <div>
        <div class="info-item"><b>订单号：</b>{{ order.orderNo }}</div>
        <div class="info-item"><b>游玩日期：</b>{{ order.orderYwrq }}</div>
        <div class="info-item"><b>取票人：</b>{{ order.orderQpname }}</div>
        <div class="info-item"><b>手机号：</b>{{ order.orderQprsj }}</div>
      </div>
      <div>
        <div class="info-item"><b>门票数量：</b>{{ order.orderCount }}张</div>
        <div class="info-item"><b>订单状态：</b>
          <el-tag :type="getStatusType(order.orderState)">{{ getStatusText(order.orderState) }}</el-tag>
        </div>
        <div class="info-item"><b>支付方式：</b>{{ mapPayType(order.orderPtype) }}</div>
      </div>
    </div>
    <div class="amount">应付金额：￥{{ fmtMoney(totalAmount) }}</div>
  </el-card>

  <!-- 微信支付方式选择 -->
  <el-card shadow="always" style="margin-bottom:14px;" v-if="order && order.orderState === '11'">
    <div class="title">选择支付方式</div>
    <div class="pay-method" :class="{active: selectedPayMethod === 'wechat'}" @click="selectPayMethod('wechat')">
      <i class="el-icon-chat-dot-square" style="font-size:24px; color:#09bb07;"></i>
      <div>微信支付</div>
    </div>

    <el-button type="primary" size="large" style="width:100%; margin-top: 20px;" @click="createPayment" :loading="creating">
      立即支付
    </el-button>
    <!-- 添加暂不支付按钮 -->
    <el-button type="info" size="large" style="width:100%; margin-top: 10px; margin-left: 0px;" @click="goToIndex">
      暂不支付
    </el-button>
  </el-card>

  <!-- 二维码支付 -->
  <el-card shadow="always" v-if="showQRCode" style="margin-bottom:14px;">
    <div class="title">扫码支付</div>
    <div class="qr-container">
      <div class="countdown" v-if="countdown > 0">
        支付剩余时间：{{ Math.floor(countdown/60) }}:{{ (countdown%60).toString().padStart(2,'0') }}
      </div>
      <!-- 使用vue-qriously组件生成二维码 -->
      <qriously v-if="code_url" :value="code_url" :size="200" />
      <p style="color:#909399; margin:10px 0;">请使用微信扫描二维码完成支付</p>
      <el-button @click="refreshPayStatus" :loading="checking">手动刷新支付状态</el-button>
    </div>
  </el-card>

  <!-- 支付状态 -->
  <el-card shadow="always" v-if="paymentStatus === 'SUCCESS'">
    <div class="pay-status">
      <i class="el-icon-success" style="font-size:60px; color:#67c23a;"></i>
      <h2 style="color:#67c23a; margin:20px 0;">支付成功！</h2>
      <p>您的订单已支付完成，请保存好订单信息</p>
      <el-button type="primary" @click="goToOrders">查看我的订单</el-button>
    </div>
  </el-card>

  <!-- 底部操作 -->
  <div class="footer-bar" v-if="order && order.orderState === '11' && !showQRCode">
    <div style="color:#909399;">
      <i class="el-icon-info"></i>
      订单将在2分钟内自动取消
    </div>
  </div>
</div>

<script>

  new Vue({
    el: '#app',
    data() {
      return {
        orderNo: null,
        order: null,
        loading: false,
        creating: false,
        checking: false,
        selectedPayMethod: 'wechat',
        showQRCode: false,
        paymentStatus: '', // NOTPAY, SUCCESS, FAIL
        countdown: 0,
        countdownTimer: null,
        statusTimer: null,
        qrCodeInstance: null,
        code_url: "" // 添加code_url字段用于存储二维码链接
      };
    },
    computed: {
      totalAmount() {
        return this.order ? this.order.orderTprice : 0;
      }
    },
    mounted() {
      // 从URL获取订单号
      const sp = new URLSearchParams(location.search);
      this.orderNo = sp.get('orderNo');
      if (!this.orderNo) {
        this.$message.error('缺少订单号参数');
        this.goBack();
        return;
      }
      this.loadOrderInfo();
    },
    beforeDestroy() {
      // 清理定时器
      if (this.countdownTimer) clearInterval(this.countdownTimer);
      if (this.statusTimer) clearInterval(this.statusTimer);
    },
    methods: {
      // 加载订单信息
      loadOrderInfo() {
        this.loading = true;
        axios.get("/order/queryByNo/"+this.orderNo)
                .then(res => {
                  if (res.data && res.data.code === 200) {
                    this.order = res.data.data;
                    // 如果订单已支付，直接显示成功状态
                    if (this.order.orderState === '12') {
                      this.paymentStatus = 'SUCCESS';
                      // 支付成功的订单需要清理定时器
                      if (this.countdownTimer) clearInterval(this.countdownTimer);
                      if (this.statusTimer) clearInterval(this.statusTimer);
                      this.countdownTimer = null;
                      this.statusTimer = null;
                    }
                  } else {
                    this.$message.error(res.data.msg || '获取订单信息失败');
                  }
                })
                .catch(err => {
                  this.$message.error('请求失败：' + err.message);
                })
                .finally(() => {
                  this.loading = false;
                });
      },

      // 选择支付方式（只保留微信支付）
      selectPayMethod(method) {
        this.selectedPayMethod = method;
      },

      // 创建支付
      createPayment() {
        // 只有在倒计时未启动时才创建支付
        if (this.countdownTimer) {
          return;
        }
        
        // 只支持微信支付
        this.createWechatPay();
      },

      // 创建微信支付
      createWechatPay() {
        this.creating = true;
        // 限制商品描述长度，避免超过微信支付限制
        let payDescription = '景区门票订单支付';
        if (this.order && this.order.orderNo) {
          payDescription = '订单-' + this.order.orderNo.substring(this.order.orderNo.length - 10);
        }
        
        const payData = {
          orderNo: this.orderNo,
          payPje: this.totalAmount,
          payFullmsg: payDescription
        };

        axios.post("/pay/createNative", payData)
                .then(response => {
                  if (response.data.code === 200) {
                    // 使用与后端管理页面相同的方式处理二维码
                    this.code_url = response.data.data.code_url;
                    this.showQRCode = true;
                    this.paystatus = "等待支付，请扫码";

                    // 只有在倒计时未启动时才启动倒计时和轮询
                    if (!this.countdownTimer) {
                      this.startCountdown();
                      this.startStatusPolling();
                    }
                  } else {
                    this.$message.error("支付创建失败: " + (response.data.msg || response.data.message));
                    this.showQRCode = false;
                  }
                })
                .catch(error => {
                  console.error("创建支付失败：", error);
                  // 特别处理订单号重复的情况
                  if (error.response && error.response.data && 
                      typeof error.response.data === 'string' && 
                      error.response.data.includes('商户订单号重复')) {
                    this.$message.error("该订单已创建支付，请不要重复提交支付请求");
                  } else {
                    this.$message.error("网络错误: " + (error.response?.data?.msg || error.message));
                  }
                  this.showQRCode = false;
                })
                .finally(() => {
                  this.creating = false;
                });
      },

      // 开始倒计时
      startCountdown() {
        // 只有在倒计时未启动时才设置初始值
        if (!this.countdownTimer) {
          this.countdown = 2 * 60; // 2分钟
          this.countdownTimer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer);
              this.countdownTimer = null;
              this.$message.warning('支付超时，请重新创建支付');
              this.showQRCode = false;
            }
          }, 1000);
        }
      },

      // 开始状态轮询
      startStatusPolling() {
        // 只有在轮询未启动时才启动
        if (!this.statusTimer) {
          this.statusTimer = setInterval(() => {
            this.queryPayStatus();
          }, 3000); // 每3秒查询一次
        }
      },

      // 查询支付状态
      queryPayStatus() {
        axios.get(`/pay/queryStatus/${this.orderNo}`)
                .then(response => {
                  if (response.data.code === 200) {
                    const tradeState = response.data.data;
                    // 映射微信支付状态为中文提示
                    const statusMap = {
                      'SUCCESS': '支付成功',
                      'NOTPAY': '等待支付，请扫码',
                      'USERPAYING': '用户支付中',
                      'CLOSED': '支付已关闭',
                      'PAYERROR': '支付失败'
                    };
                    // this.paystatus = statusMap[tradeState] || '未知状态';

                    // 支付成功：停止轮询、更新列表、关闭弹窗
                    if (tradeState === 'SUCCESS') {
                      this.paymentStatus = 'SUCCESS';
                      this.showQRCode = false;
                      if (this.countdownTimer) clearInterval(this.countdownTimer);
                      if (this.statusTimer) clearInterval(this.statusTimer);
                      this.countdownTimer = null;
                      this.statusTimer = null;
                      this.$message.success('支付成功！');
                      this.loadOrderInfo(); // 刷新订单列表
                    }
                    // 支付关闭或失败：停止轮询
                    else if (['CLOSED', 'PAYERROR'].includes(tradeState)) {
                      if (this.statusTimer) clearInterval(this.statusTimer);
                      this.statusTimer = null;
                    }
                  } else {
                    this.$message.error('查询支付状态失败: ' + (response.data.msg || response.data.message));
                  }
                })
                .catch(error => {
                  console.error('查询支付状态出错: ', error);
                  this.$message.error('网络错误，无法查询支付状态');
                });
      },

      // 手动刷新支付状态
      refreshPayStatus() {
        this.checking = true;
        this.queryPayStatus();
        setTimeout(() => {
          this.checking = false;
        }, 1000);
      },

      // 获取状态类型
      getStatusType(status) {
        const map = {
          '11': 'warning',  // 待付款
          '12': 'success',  // 已付款
          '13': 'info',     // 已消费
          '14': 'danger'    // 已取消
        };
        return map[status] || 'info';
      },

      // 获取状态文本
      getStatusText(status) {
        const map = {
          '11': '待付款',
          '12': '已付款',
          '13': '已消费',
          '14': '已取消'
        };
        return map[status] || status;
      },

      // 支付方式映射
      mapPayType(ptype) {
        const map = { '1': '景区支付', '2': '网上支付' };
        return map[ptype] || '网上支付';
      },

      // 格式化金额
      fmtMoney(v) {
        return Number(v || 0).toFixed(2);
      },

      // 返回首页
      goToIndex() {
        window.location.href = 'index.html';
      },

      // 跳转到我的订单
      goToOrders() {
        window.location.href = 'order.html';
      },

      // 返回
      goBack() {
        history.back();
      }
    }
  });
</script>
</body>
</html>